#!/usr/bin/env python
# coding=utf8
import redis
import json
import urllib
import time
import requests
import sys
import datetime
import random
import string
from log import Log
from pykafka import KafkaClient


# 初始化日志对象
logger = Log('csmj')

# 初始化kafka
with open("config/config.json", 'r') as f:
    config = f.read()
config = json.loads(config)
config = config['config']

# 获取kafka消息
input = 'game_csmj'
client = KafkaClient(hosts=config['kafka_config']['host'] + ':' + config['kafka_config']['port'])
topic = client.topics[input]
consumer = topic.get_balanced_consumer(consumer_group='game_csmj_group',
                                       auto_commit_enable=True,
                                       auto_commit_interval_ms=1,
                                       zookeeper_connect='172.18.197.34:2181')
                                       

# 初始化redis
r = redis.Redis(host=config['redis_config']['host'],
                port=config['redis_config']['port'], db=3,
                password=config['redis_config']['pass'])

try:
    r.ping()
except redis.exceptions.ConnectionError:
    logger.debug('redis db3 connect error')

# 判断redis是否还存在reportToken
if r.ping():
    if r.exists("report_token"):
        token = r.hget('report_token', 'token')
    else:
        url = config['report_config']['get_token_url']
        param = {'data': {'cid': config['report_config']['cid'],
                          'username': config['report_config']['user'],
                          'passwd': config['report_config']['pass']}}

        re = requests.post(url, data=json.dumps(param))
        respJson = re.json()
        if respJson['code'] == 200:
            r.hset('report_token', 'token', respJson['info'])
            r.expire('report_token', 43200)
            token = respJson['info']
        else:
            logger.debug('获取token失败')

# 初始化redis
r = redis.Redis(host=config['redis_config']['host'],
                port=config['redis_config']['port'], db=0,
                password=config['redis_config']['pass'])

try:
    r.ping()
except redis.exceptions.ConnectionError:
    logger.debug('redis db0 connect error')


for message in consumer:
    if r.ping():
        if message is not None:
            try:
                dicts = json.loads(message.value)
                # print dicts
                logger.debug(message.value)
                action = dicts['action_type']
                uid = dicts['user_id']
                times = dicts['time']
            except Exception, e:
                uid = 0
                action = ''
                times = 0
                logger.debug(e)

            result = r.hgetall('hu:' + str(uid))
            if result:
                keys = result.keys()
                if 'imei' not in keys or not result['imei'].strip():
                    ranString = ''.join(random.choice(string.ascii_letters) for x in range(16))
                    result['imei'] = ranString
                if 'channel' not in keys or not result['channel'].strip():
                    result['channel'] = 1
                if 'agent' not in keys or not result['agent'].strip():
                    result['agent'] = 'baidu'

                # 退出消息
                if action == 4:
                    r.hset('hu:' + str(uid), 'heartbeat_at', int(times))
                    param = {'cid': config['report_config']['cid'], 'user_id': result['id'],
                             'logout_time': result['heartbeat_at'], 'imei': result['imei'],
                             'platform_type': result['platform_type'], 'channel': result['channel'], 'agent': result['agent'],
                             'user_name': result['name'], 'user_level': 1, 'vip_level': 1, 'ip': result['login_ip'],
                             'ua': result['device_num']
                             }
                    url = config['report_config']['report_logout_url']
                    data = {'cid': config['report_config']['cid'], 'secret_key': token, 'data': [param]}
                    re = requests.post(url, data=json.dumps(data))
                    logger.debug('退出', re.json())

                # 房卡消息
                if action == 5:
                    param = {'cid': config['report_config']['cid'], 'user_id': result['id'],
                             'cons_time': int(dicts['time']), 'imei': result['imei'],
                             'good_type': 1, 'channel': result['channel'], 'agent': result['agent'],
                             'cons_type': 1, 'cons_num': 1, 'consable_times': 1
                             }
                    url = config['report_config']['report_vgoods_url']
                    data = {'cid': config['report_config']['cid'], 'secret_key': token, 'data': [param]}
                    re = requests.post(url, data=json.dumps(data))
                    logger.debug('消费房卡: ', re.json())
            else:
                logger.debug('uid is not exists')

